package login.ops;

import org.slf4j.LoggerFactory;
import sun.security.pkcs.ParsingException;
import tr.gov.tubitak.uekae.esya.api.smartcard.signature.pkcs.PKCS7;
import tr.gov.tubitak.uekae.esya.api.smartcard.signature.pkcs.SignerInfo;

import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;

/**
 * Provides operations for PKCS7 signature
 *
 * @author suleyman.uslu
 */
public class PKCS7SignatureOps implements SignatureOps {

    private static org.slf4j.Logger msLogger = LoggerFactory.getLogger(PKCS7SignatureOps.class);

    private PKCS7 signature;

    public PKCS7SignatureOps(byte[] signatureBytes) {

        try {
            signature = new PKCS7(signatureBytes);
        } catch (ParsingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean verify() {

        try {
            SignerInfo[] signerInfo = signature.verify();
            if(signerInfo == null)
                return false;
            else
                return true;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String getSignerName() {

        return signature.getCertificates()[0].getSubjectX500Principal().getName();
    }
}
